//
//  Mytools.m
//  7UGame
//
//  Created by 111 on 2017/2/14.
//  Copyright © 2017年 111. All rights reserved.
//

#import "Mytools.h"
#import <CommonCrypto/CommonDigest.h>
#import <AssetsLibrary/AssetsLibrary.h>

 
@implementation Mytools
+(NSString *)getMD5code:(NSString *)pswStr{
    NSString *resultStr = nil;//加密后的结果
    const char *cStr = [pswStr UTF8String];//指针不能变，cStr指针变量本身可以变化
    unsigned char result[16];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
    resultStr = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                 result[0], result[1], result[2], result[3],
                 result[4], result[5], result[6], result[7],
                 result[8], result[9], result[10], result[11],
                 result[12], result[13], result[14], result[15]
                 ];
    return resultStr;
}
+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}
+(void)saveImageToLocal:(UIImage *)img{
    Mytools * file = [Mytools new];
    UIImageWriteToSavedPhotosAlbum(img, file, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
    }else{
        [QMUITips showError:@"图片保存失败"];
    }
}
+(UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}
+(void)NeedResetNoViewWithTable:(UITableView*)tab andArr:(NSMutableArray*)arr{
    if (arr.count>0) {
        [tab dismissNoView];
    }else{
        [tab dismissNoView];
        [tab showNoView:@"暂无数据" image:Image(@"暂无数据") certer:CGPointZero];
    }
}
+(NSString*)getCurrentTimestamp{
    //获取系统当前的时间戳
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSInteger newA = a;
    NSString * timeString = [NSString stringWithFormat:@"%ld", (long)newA];
    return timeString;
}

+(NSDate *)getCurrentDate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    NSDate *destDate= [formatter dateFromString:dateTime];
    return destDate;
    
}

+(NSString*)encodeString:(NSString*)unencodedString{
    NSString * encodedStr = (NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)unencodedString,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
    return encodedStr;
}
+ (NSString *)timeStampTotime:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone systemTimeZone];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
//字符串转日期
+(NSDate*)dateStrToDate:(NSString *)dateStr{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date =[dateFormat dateFromString:dateStr];
    return date;
}
+(NSString *)dateToDateStr:(NSDate*)date{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormat stringFromDate:date];
    return currentDateStr;
}

#pragma mark json格式字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark 字典转json格式字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

#pragma mark 数组转json格式字符串
+ (NSString*)ArrtionaryToJson:(NSMutableArray *)arr
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

//日期大小比较
+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
//    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result ==NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}

+(BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//去掉utc时间
+ (NSString *)htcTimeToLocationStr:(NSString*)strM
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //输入格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    NSDate *dateFormatted = [dateFormatter dateFromString:strM];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *locationTimeString=[dateFormatter stringFromDate:dateFormatted];
    return locationTimeString;
}
//字符串转图片

+ (CGSize)sizeWithSizeStr:(NSString *)sizeStr
{
    CGSize imageSize = CGSizeMake(1, 1);
    NSArray *sizeArray = [sizeStr componentsSeparatedByString:@"*"];
    if (sizeArray && [sizeArray isKindOfClass:[NSArray class]] && sizeArray.count == 2) {
        imageSize = CGSizeMake([sizeArray[0] floatValue], [sizeArray[1] floatValue]);
    }
    return imageSize;
}

+(NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3)){
        return 28;
    }
    if(year % 400 == 0)
        return 29;
    if(year % 100 == 0)
        return 28;
    return 29;
}
+(NSString*)returnDecimalNumStr:(NSString*)numStr{
    NSString *doubleString  = [NSString stringWithFormat:@"%lf", [numStr doubleValue]];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}
+(NSArray *)filterUrlWithString:(NSString*)str{
    NSString * prex = @"(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
    NSError*error;
    NSRegularExpression*regex = [NSRegularExpression regularExpressionWithPattern:prex options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray*arrayOfAllMatches = [regex matchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, str.length)];
    NSMutableArray * arr = [NSMutableArray new];
    for(NSTextCheckingResult*match in arrayOfAllMatches){
        NSString* substringForMatch = [str substringWithRange:match.range];
        [arr addObject:substringForMatch];
    }
    return arr.copy;
}
@end
